package compress

import (
	"archive/tar"
	"changeme/backend/utils"
	"fmt"
	"github.com/ulikunitz/xz"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
)

func Xz(path string, createPath string) (err error) {
	if _, exist := utils.Exist(path); !exist {
		return fs.ErrNotExist
	}

	xzFile, err := os.OpenFile(createPath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0755)
	defer func() {
		_ = xzFile.Close()
	}()
	if err != nil {
		return err
	}

	xzWriter, err := xz.NewWriter(xzFile)
	if err != nil {
		return
	}
	defer func() {
		_ = xzWriter.Close()
	}()
	return xzCompress(path, xzWriter)
}

func xzCompress(path string, w *xz.Writer) (err error) {
	if _, exist := utils.Exist(path); !exist {
		return fs.ErrNotExist
	}

	tarWriter := tar.NewWriter(w)
	defer func() {
		_ = tarWriter.Close()
	}()

	return TarCompress("", path, tarWriter)
}

func UnXz(absFilePath string, extractPath string) (err error) {
	if !utils.ExistFile(absFilePath) {
		return fs.ErrNotExist
	}

	xzFile, err := os.Open(absFilePath)
	defer func() {
		_ = xzFile.Close()
	}()
	if err != nil {
		return err
	}
	xzReader, err := xz.NewReader(xzFile)
	if err != nil {
		return err
	}

	abs, _ := filepath.Abs(extractPath)
	xzFileName := strings.TrimSuffix(filepath.Base(absFilePath), ".xz")
	if !utils.EndWith(xzFileName, ".tar") {
		xzFileName += ".tar"
	}
	tarFilePath := filepath.Join(abs, xzFileName)
	tarFile, err := os.OpenFile(tarFilePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0755)
	defer func() {
		_ = tarFile.Close()
	}()

	fmt.Printf("解压 %s \n\t=> %s\n", absFilePath, tarFilePath)
	_, err = io.Copy(tarFile, xzReader)
	if err != nil {
		return err
	}

	return
}
